package com.ccp.dev.qbdms.service;

import static com.ccp.dev.system.service.SysFileService.getBasePath;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.response.ReturnCode;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.extend.model.ExtendSysFile;
import com.ccp.dev.extend.service.ExtendAttachmentSysFileService;
import com.ccp.dev.qbdms.annotation.IsAttachment;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.model.SysOrgDeploy;
import com.ccp.dev.qbdms.util.HttpSendUtil;
import com.ccp.dev.qbdms.util.ReadAttachmentUtil;
import com.ccp.dev.qbdms.webservice.cxf.CxfClient;
import com.google.common.collect.Maps;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * ClassDescribe:读取，写入附件逻辑
 *
 * @author :milihao
 */
@Service
public class AttachmentService {

	private static final Logger LOGGER = LoggerFactory.getLogger(AttachmentService.class);
	@Resource
	private ExtendAttachmentSysFileService extendAttachmentSysFileService;

	public boolean sendAttachments(Map<String, Object> paramMap, String modelName,
			SysOrgDeploy deployment) throws Throwable {
		JSONObject jsonObj = JSONObject.parseObject(
				JSON.toJSONString(paramMap));
		JSONArray listObj = jsonObj.getJSONArray(ZhiLiangConst.API_REPORT_PARA_LIST);
		modelName = CxfClient.getClassName(modelName);
		Class<?> clazz1 = Class.forName("com.ccp.dev.qbdms.model." + modelName);
		List<?> list = listObj.toJavaList(clazz1);
		String httpUrl = ZhiLiangConst.API_URL_RECEIVE_ATTACHMENT;
		getExtendSysFileList(list, deployment, httpUrl);
		return true;
	}

	public void writeAttachment(List<ExtendSysFile> extendSysFileList) {
		for (ExtendSysFile extendSysFile : extendSysFileList) {
			String[] filePath;
			if (ReadAttachmentUtil.isWindows()) {
				filePath = extendSysFile.getFilePath().split("\\\\");
			} else {
				filePath = extendSysFile.getFilePath().split("/");
			}
			String savePath = PropertyUtil.getByAlias("file.upload") + "/";
			for (int i = 0; i < filePath.length - 1; i++) {
				savePath += filePath[i] + "/";
			}
			File file = new File(savePath);
			if (!file.exists()) {
				File file1 = new File(savePath);
				file1.mkdirs();
			}
			savePath += filePath[filePath.length - 1];
			ReadAttachmentUtil
					.stringSaveAsFile(extendSysFile.getAttachmentStrContent(),
							savePath);
			extendSysFile.setAttachmentStrContent(null);
			extendAttachmentSysFileService.delById(extendSysFile.getFileId());
			extendAttachmentSysFileService.add(extendSysFile);
		}
	}

	/**
	 * 获取fileList
	 *
	 * @param list list
	 * @param <T> T
	 * @return List<SysFile>
	 */
	private <T> List<ExtendSysFile> getExtendSysFileList(List<T> list, SysOrgDeploy deployment,
			String httpUrl) throws Throwable {
		for (T t : list) {
			packageExtendSysFileList(t, deployment, httpUrl);
		}
		return Lists.newArrayList();
	}

	private <T> T packageExtendSysFileList(T t, SysOrgDeploy deployment, String httpUrl)
			throws IllegalAccessException, IOException {
		Field[] fields = t.getClass().getDeclaredFields();
		for (Field field : fields) {
			if (field.isAnnotationPresent(IsAttachment.class)) {
				field.setAccessible(true);
				String value = null;
				if (null == field.get(t)) {
					continue;
				}
				IsAttachment isAttachment = field.getAnnotation(IsAttachment.class);
				if (isAttachment.isSubTable()) {
					List<T> tList = (List) field.get(t);
					for (T t1 : tList) {
						packageExtendSysFileList(t1, deployment, httpUrl);
					}
				} else {
					try {
						value = (String) field.get(t);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
					List<Map> mapList = JSON.parseArray(value, Map.class);
					sendExtendSysFileList(mapList, deployment, httpUrl);
				}
			}
		}
		return t;
	}

	/**
	 * 根据FileId获取file
	 *
	 * @param mapList fileId
	 * @return List<SysFile>
	 */
	private void sendExtendSysFileList(List<Map> mapList, SysOrgDeploy deployment, String httpUrl)
			throws IOException {
		ExtendSysFile extendSysFile;
		if (null != mapList) {
			for (Map<String, Object> map : mapList) {
				if (null != map.get("fileId")) {
					extendSysFile = extendAttachmentSysFileService
							.getOneById(String.valueOf(map.get("fileId")));
					extendSysFile.setAttachmentStrContent(ReadAttachmentUtil.fileToString(
							getBasePath().replace("/", File.separator) + "/" + extendSysFile
									.getFilePath()));
					sendAttachment(extendSysFile, deployment, httpUrl);
				}
			}
		}
	}

	private void sendAttachment(ExtendSysFile extendSysFile, SysOrgDeploy deployment,
			String httpUrl) {
		if (BeanUtils.isNotEmpty(deployment) && ZhiLiangConst.DEPMETHOND_CLASS
				.equals(deployment.getDepmethod())) {
			List<ExtendSysFile> extendSysFileList = Lists.newArrayList();
			extendSysFileList.add(extendSysFile);
			String url =
					deployment.getUrl() + ZhiLiangConst.URL_API + ZhiLiangConst.URL_VERSION + httpUrl;
			LOGGER.info("通用发送附件---------> 接口地址: {}", url);
			Map<String, Object> param = Maps.newHashMap();
			param.put(ZhiLiangConst.API_REPORT_PARA_LIST_FILE, extendSysFileList);
			ResponseEntity<JSONObject> response = HttpSendUtil
					.httpRestClient(url, HttpMethod.POST, param);
			if (response.getStatusCode() != HttpStatus.OK
					|| (int) response.getBody().get("code") != ReturnCode.SUCCESS.getCode()) {
				LOGGER.error("通用发送附件服务异常---------> API接口调用失败! 详细:{}", response.toString());
			}
		}
	}

}
